package com.v5ba.encryptserver.common;

import org.springframework.util.DigestUtils;

/**
 * 随机字符串
 * @author yiren
 * @date 2018/6/17
 */
public class GengerCode {

    private static final char[] BASE_NUM_CODES = {'0','1','2','3','4','5','6','7','8','9'};
    private static final char[] BASE_CODES = {
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
            'S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j',
            'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1',
            '2','3','4','5','6','7','8','9'};

    public static String getCodeForNum(int length) {
        return generateCode(length, BASE_NUM_CODES);
    }

    public static String getCode(int length) {
        return generateCode(length, BASE_CODES);
    }

    public static String generateCode(int length, char[] code) {
        StringBuffer randomCode = new StringBuffer();
        int charLen = code.length;
        for(int i = 0; i < length; ++i) {
            Double dNum = Math.random() * charLen;
            randomCode.append(code[dNum.intValue()]);
        }
        return randomCode.toString();
    }
    public static String md5(String code){
        return DigestUtils.md5DigestAsHex(code.getBytes());
    }
}

